# -*- coding: utf-8 -*-
# @Date：2024/8/6 16:11:13
# @Author：CJiaの青姝
# @FileName：error_log
# @Editor：PyCharm2024
# @Remark：
from typing import List

from logs.models import ErrorLog
from ninja import Router, Field, Query, ModelSchema
from ninja.pagination import paginate

from utils.cj_ninja import CjFilters, MyPagination
from utils.cj_crud import create, batch_create, delete, batch_delete, update, condition, single
from utils.cj_export import export_data, repeat_data, deal_chinese_key
from utils.cj_response import SuccessResponse, ErrorResponse

router = Router()


class Filters(CjFilters):
    request_username: str = Field(None, description="异常用户", alias='request_username')

    class Config:
        title = "异常日志查询参数"


class ErrorLogSchemaOut(ModelSchema):
    key: int = Field(None, description="唯一标识符", alias='key')

    class Config:
        title = "异常日志实例"
        model = ErrorLog
        model_fields = "__all__"


@router.delete("/error_log/{error_log_id}", response=ErrorLogSchemaOut, summary="删除日志")
def delete_error_log(request, error_log_id: int):
    """ 删除日志 """
    # 调用删除方法
    result, code = delete(ErrorLog, error_log_id)
    if code != 200:
        return ErrorResponse(code=code, msg=result)
    # 返回结果
    return SuccessResponse(data=result, msg="删除成功")


@router.delete("/error_log/batch/del", summary="批量删除日志")
def batch_delete_login_log(request, ids: List[int]):
    """ 批量删除日志 """
    # 调用批量删除方法
    result = batch_delete(request, ErrorLog, ids)
    # 返回结果
    return SuccessResponse(data=result, msg="批量删除成功")


class ErrorLogSchemaOut(ModelSchema):
    key: int = Field(None, description="唯一标识符", alias='key')

    class Config:
        title = "异常日志实例"
        model = ErrorLog
        model_fields = "__all__"


@router.delete("/error_log/{error_log_id}", response=ErrorLogSchemaOut, summary="删除日志")
def delete_error_log(request, error_log_id: int):
    """ 删除日志 """
    # 调用删除方法
    result, code = delete(ErrorLog, error_log_id)
    if code != 200:
        return ErrorResponse(code=code, msg=result)
    # 返回结果
    return SuccessResponse(data=result, msg="删除成功")


@router.delete("/error_log/batch/del", summary="批量删除日志")
def batch_delete_error_log(request, ids: List[int]):
    """ 批量删除日志 """
    # 调用批量删除方法
    result = batch_delete(request, ErrorLog, ids)
    # 返回结果
    return SuccessResponse(data=result, msg="批量删除成功")


@router.get("/error_log", response=List[ErrorLogSchemaOut], summary="获取分页异常日志列表")
@paginate(MyPagination)
def list_error_log(request, filters: Filters = Query(...)):
    """ 获取分页异常日志列表 """
    # 调用分页方法
    result = condition(request, ErrorLog, filters)
    # 返回结果
    return result


@router.get("/error_log/{error_log_id}", response=ErrorLogSchemaOut, summary="获取异常日志")
def get_error_log(request, error_log_id: int):
    """ 获取异常日志 """
    # 调用根据id获取指定对象方法
    result = single(request, ErrorLog, id=error_log_id)
    # 返回结果
    return SuccessResponse(data=result)
